package com.coder520.sync_learning.demo.flyquery;

import com.coder520.sync_learning.demo.Cache;
import sun.font.CreatedFontTracker;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class FightQueryExample {
    //合作的航班
    private static List<String> fightCompany= Arrays.asList("csa","cea","hna");

    public static void main(String[] args){
        List<String> results=search("sh","bj");
        System.out.println("=============results===============|");
        results.forEach(System.out::println);
    }

    private static List<String> search(String original, String dest) {
        final List<String>  result=new ArrayList<>();

        //创建查询航班信息的列表
        List<FightQueryTask> tasks=fightCompany.stream().map(f -> createSeachTask(f,original,dest)).collect(toList());

        //启动这几个线程
        tasks.forEach(Thread :: start);

        //分别调用当前线程的join方法，阻塞当前线程
        tasks.forEach(t -> {
            try {
                t.join();
            }catch (InterruptedException e){

            }
        });

        //再此之前，当前的线程会阻塞住，获取到每个查询线程的结果，并且加入到result中
        tasks.stream().map(FightQuery::get).forEach(result::addAll);

        return result;

   }

    private static FightQueryTask createSeachTask(String f, String original, String dest) {
        return new FightQueryTask(f,original,dest);
    }
}
